package cn.itcast.goods.user.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.commons.CommonUtils;
import cn.itcast.goods.user.domain.User;
import cn.itcast.goods.user.service.UserException;
import cn.itcast.goods.user.service.UserService;
import cn.itcast.servlet.BaseServlet;

public class UserServlet extends BaseServlet {
	
	private UserService userService=new UserService();
	/*
	 * 异步校验登录名
	 * 
	 * request
	 * response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * */
	public String validateLoginname(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
	
		String loginname=request.getParameter("loginname");
		boolean flag=userService.validateLoignname(loginname);
		//如果登录名已被注册返回空
		response.getWriter().print(flag+"");
		
		return null;
		
	}
	/*
	 * 异步校验email
	 * 
	 * request
	 * response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * */
	public String validateEmail(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
		
		String email=request.getParameter("email");
		boolean flag=userService.validateLoignname(email);
		//如果Email已被注册返回空
		response.getWriter().print(flag+"");
		
		return null;
		
	}
	/*
	 * 异步校验验证码
	 * 
	 * request
	 * response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * */
	public String validateVerifyCode(HttpServletRequest request,HttpServletResponse response)  throws ServletException, IOException  {
		String vCode=(String)request.getSession().getAttribute("vCode");
	    String verifyCode=request.getParameter("verifyCode");
	    boolean flag=vCode.equalsIgnoreCase(verifyCode);//如果验证成功返回true
	    response.getWriter().print(flag+"");
		return null;	
	}
	
	/*
	 * 注册
	 * 
	 * */
	public String regist(HttpServletRequest request,HttpServletResponse response)  
			throws ServletException, IOException {
		//1.封装表单数据到User对象中
		User user=CommonUtils.toBean(request.getParameterMap(), User.class);
		//2.对表单数据进行服务器校验
		Map<String,String> errors=validateRegist(user,request);
		if(errors!=null&&errors.size()>0){
			request.setAttribute("errors",errors);
			request.setAttribute("user", user);
			return "f:/jsps/user/regist.jsp";
		}
		//3.调用userservice完成注册
		userService.regist(user);
		//4.保存注册成功信喜，转发到msg.jsp显示
		request.setAttribute("code","success");//是成功信息还是错误信息
		request.setAttribute("msg", "恭喜，注册成功，请马上到邮箱完成激活！");
		return "f:/jsps/msg.jsp";

	}
	
	/*
	 * 服务器端表单校验
	 * 如果校验通过，返回长度为0的Map，如果校验失败，那么返回的Map中保存的是错误信息。
	 *   Map中key为字段名称，值为错误信息。
	 */
	private Map<String, String> validateRegist(User user,
			HttpServletRequest request) {
		Map<String,String> errors=new HashMap<String, String>();
		//对loginname进行校验
		String loginname=user.getLoginname();
		if(loginname==null||loginname.isEmpty()){
			errors.put("loginname","用户名不能为空！");
		}else if(loginname.length()<3||loginname.length()>20){
			errors.put("loginname", "用户名长度必须在3~20位之间");
		}else if(userService.validateLoignname(loginname)){
			errors.put("loginname", "用户名已被注册过！");
		}
		
		
		//对loginpass进行校验
		String loginpass=user.getLoginpass();
		if(loginpass==null||loginpass.isEmpty()){
			errors.put("loginpass", "密码不能为空！");			
		}else if(loginpass.length()<3||loginpass.length()>20){
			errors.put("loginpass", "密码长度必须在3~20位之间!");
		}
		
		
		//对确认密码进行校验
		String reloginpass=user.getReloginpass();
		if(reloginpass==null||reloginpass.isEmpty()){
			errors.put("reloginpass", "确认密码不能为空！");
		}else if(!reloginpass.equals(loginpass)){
			errors.put("reloginpass", "两次输入的密码不......一致！");
		}
		
		
		//对email进行校验
		String email=user.getEmail();
		if(email==null||email.isEmpty()){
			errors.put("email", "Email不能为空！");
		}else if(!email.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$")){
			errors.put("email", "错误的邮箱格式！");
		}else if(userService.validateEmail(email)){
			errors.put("email", "邮箱已被注册过！");
		}
		//对验证码进行校验
		String verifyCode=user.getVerifyCode();
		String vCode=(String) request.getSession().getAttribute("vCode");
		if(verifyCode==null||verifyCode.isEmpty()){
			errors.put("verifyCode", "验证码不能为空！");
		}else if(verifyCode.length()!=4){
			errors.put("verifyCode", "错误的验证码");
		}else if(!verifyCode.equalsIgnoreCase(vCode)){
			errors.put("verifyCode","错误的验证码！");
		}
		return errors;
	}
	/*
	 * 激活功能
	 * 
	 * 
	 * */
	public String activation(HttpServletRequest request ,HttpServletResponse response)
    throws ServletException, IOException{
		//1.获取激活码
		String activationCode=request.getParameter("activationCode");
		//调用userService的activation方法完成激活操作
		try {
			//2.调用userService的activation方法完成激活操作
			userService.activation(activationCode);
			//3.如果没有抛出异常，那么保存成功信息
			request.setAttribute("code", "success");
			request.setAttribute("msg","恭喜，激活成功，请马上登录！");
		} catch (UserException e) {
			// TODO Auto-generated catch block
			//4、如果抛出了异步，保存错误信息
			request.setAttribute("code", "error");
			request.setAttribute("msg", e.getMessage());
		}
		
		//无论是成功还是失败，都会转发到msg.jsp显示消息。
		return "f:/jsps/msg.jsp";
		
	}
	/**
	 * 登录功能
	 * 
	 * 
	 * */
	public String login(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
	
		//1.封装表单数据到user对象中
		User formBean=CommonUtils.toBean(request.getParameterMap(), User.class);
		//2.对formbean进行服务器表单校验
		Map<String,String > errors=validateLogin(formBean,request);
		if(errors!=null && errors.size()>0){//是否存在错误的验证消息
			request.setAttribute("errors",errors );
			request.setAttribute("user", formBean);
			return "f:/jsps/user/login.jsp";
			
		}
		
		//3.调用userService#login（USer user)完成登录
		User user=userService.login(formBean);
		//4.判断是否查询到User
		if(user==null){//如果用户登录失败
			request.setAttribute("user", formBean);
			request.setAttribute("msg", "用户名或密码错误");
			return "f:/jsps/user/login.jsp";
		}else if(!user.isStatus()){//如果用户还没有被激活
			request.setAttribute("user", formBean);
			request.setAttribute("msg", "您还没有激活！");
			return "f:/jsps/user/login.jsp";		
		}else {//如果登录成功
			request.getSession().setAttribute("sessionUser", user);
			//保存cookie，为了login.jsp页面可以记住当前用户名
			String name="loginname";
			String value=URLEncoder.encode(user.getLoginname(),"UTF-8");
			Cookie cookie=new Cookie(name,value);
			cookie.setMaxAge(1000*60*60*24);
			response.addCookie(cookie);
			return "r:/index.jsp";//重定向到主页
		}
		
		
	}
	/**
	 * 登录校验方法
	 * 
	 * */
	private Map<String, String> validateLogin(User user,HttpServletRequest request) {
		Map<String,String> errors=new HashMap<String, String>();
		//对loginname进行校验
		String loginname=user.getLoginname();
		if(loginname==null||loginname.isEmpty()){
			errors.put("loginname", "用户名不能为空！");			
		}else if(loginname.length()<3||loginname.length()>20){
			errors.put("loginname", "用户名长度必须在3到20位之间！");
			
		}
		//对loginpass进行校验
		String loginpass=user.getLoginpass();
		if(loginpass==null || loginpass.isEmpty()){
			errors.put("loginpass", "密码不能空！");
		}else if(loginpass.length()<3||loginpass.length()>20){
			errors.put("loginpass", "密码长度必须在3到20位之间！！");
		}
		//对验证码进行校验
		String verifyCode=user.getVerifyCode();
		String vCode=(String) request.getSession().getAttribute("vCode");
		if(verifyCode==null||verifyCode.isEmpty()){
			errors.put("verifyCode", "验证码不能为空！");
		}else if(verifyCode.length()!=4){
			errors.put("verifyCode", "错误的验证码！");
		}else if(!verifyCode.equalsIgnoreCase(vCode)){
			errors.put("verifyCode", "错误的验证码！");
		}
		return errors;
	}
	
	/**
	 * 退出功能
	 * 
	 * 
	 * */
	public String quit(HttpServletRequest request,HttpServletResponse response) throws 
	ServletException,IOException{
		request.getSession().removeAttribute("sessionUser");
	
		return "r:/jsps/user/login.jsp";
		
	}
	/**
	 * 修改密码
	 * 
	 * 
	 * */
	public String  updatePassword(HttpServletRequest request,HttpServletResponse response)
			throws ServletException, IOException{
		//1.封装表单数据到user
			User formBean=CommonUtils.toBean(request.getParameterMap(), User.class);
		 
		//2.调用userservice的updatePassword(String uid,String newpass)方法修改密码
		User user=(User) request.getSession().getAttribute("sessionUser");
		
		userService.updatePassword(user.getUid(), formBean.getNewpass());
		//3.转发到msg.jsp
		
		request.setAttribute("code", "success");
		request.setAttribute("msg", "恭喜，密码修改成功！");
		return "f:/jsps/msg.jsp";
		
	}
}








	


